package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//只要正式代理(一级及二级)
func ListOfficialH5User(p ListParams, op OrderParams, groupId int64, u H5UserParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" u.status = %v", FirstTopUpSuccess) //正式代理
	if groupId != 0 {
		where = where + fmt.Sprintf(" AND u.group_id = %v", groupId)
	} else { //超级管理员
		if u.GroupId != 0 {
			where = where + fmt.Sprintf(" AND u.group_id = %v", u.GroupId)
		}
	}

	if u.Level != 0 {
		where = where + fmt.Sprintf(" AND u.level = %v", u.Level)
	}

	if u.Uid != 0 {
		where = where + fmt.Sprintf(" AND u.uid = %v", u.Uid)
	}
	if u.Phone != "" {
		where = where + fmt.Sprintf(" AND u.phone = %v", u.Phone)
	}
	if u.AgentName != "" {
		where = where + fmt.Sprintf(" AND u.nickname LIKE '%v'", "%"+u.AgentName+"%")
	}
	if u.IsPass == 1 { //考核通过
		where = where + fmt.Sprintf(" AND u.is_pass = 1")
	} else if u.IsPass == 2 { //考核不通过
		where = where + fmt.Sprintf(" AND u.is_pass = 0")
	}

	if u.IsFrozen == 1 { //冻结
		where = where + fmt.Sprintf(" AND u.frozen = 1")
	} else if u.IsFrozen == 2 { //正常
		where = where + fmt.Sprintf(" AND u.frozen = 0")
	}

	orderName := " create_time "
	order := GetOrderSort("DESC", op.Order)
	if op.OrderName != "" {
		orderName = "c." + op.OrderName
	}

	sql := fmt.Sprintf(`
		SELECT
			g.name AS group_name,
			u.*,
			c.card_num,c.amount,c.total_card_num,c.open_fee
		FROM
			%v AS u
		LEFT JOIN
			%v AS g
		ON u.group_id = g.id
		LEFT JOIN
			%v AS c
		ON u.uid = c.uid
		WHERE
			%v
		ORDER BY
			%v %v
		LIMIT ?,?
		`, TableH5User, TablePcGroup, TableH5CardCash, where, orderName, order)
	o := NewOrm(multiOrm, DBChessCenter)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS u WHERE %v`, TableH5User, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return user, count, err
	}
	return user, count, nil
}

func StatChildAgentNum(pid interface{}, multiOrm ...orm.Ormer) int64 {
	sql := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			pid = %v AND status = %v
	`, TableH5User, pid, FirstTopUpSuccess)
	o := NewOrm(multiOrm, DBChessCenter)
	var num int64
	o.Raw(sql).QueryRow(&num)
	return num
}

type UnofficialH5User struct {
	Uid        int64  `json:"uid"`
	Nickname   string `json:"nickname"`
	Phone      string `json:"phone"`
	Status     int64  `json:"status"`
	CreateTime int64  `json:"create_time"`
}

//列出所有一级未审核的代理(包换:输入授权码成功,绑定手机成功,审核通过但未激活的)
func ListAllExpireH5User() ([]UnofficialH5User, error) {
	where := fmt.Sprintf(" status IN (%v,%v,%v) AND level = %v",
		AuthCodeSuccess, BindPhoneSuccess, VerifyPass, Level1)
	sql := fmt.Sprintf(`
		SELECT
			uid,nickname,phone,status,create_time
		FROM
			%v
		WHERE
			%v
		`, TableH5User, where)
	o := NewDBOrm(DBChessCenter)
	var user []UnofficialH5User
	_, err := o.Raw(sql).QueryRows(&user)
	if CheckNoExist(err) {
		return user, nil
	}
	return user, err
}

//列出未审核的一级代理
func ListUnofficialH5User(p ListParams, phone string, uid int64, multiOrm ...orm.Ormer) ([]UnofficialH5User, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" status IN (%v,%v,%v) AND level = %v",
		AuthCodeSuccess, BindPhoneSuccess, VerifyPass, Level1) //非正式一级代理
	if uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v", uid)
	}
	if phone != "" {
		where = where + fmt.Sprintf(" AND phone = %v", phone)
	}
	sql := fmt.Sprintf(`
		SELECT
			uid,nickname,phone,status,create_time
		FROM
			%v
		WHERE
			%v
		ORDER BY
			create_time DESC
		LIMIT ?,?
		`, TableH5User, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var user []UnofficialH5User
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&user)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TableH5User, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return user, count, err
	}
	return user, count, nil
}

//代理详情
func AgentDetail(agentId int64, multiOrm ...orm.Ormer) ([]orm.Params, error) {
	sql := fmt.Sprintf(`
		SELECT
			g.name AS group_name,g.id AS group_id,
			u.*,
			c.card_num,c.amount,c.total_card_num,c.open_fee
		FROM
			%v AS u
		LEFT JOIN
			%v AS g
		ON u.group_id = g.id
		LEFT JOIN
			%v AS c
		ON u.uid = c.uid
		WHERE
			u.uid = %v
		`, TableH5User, TablePcGroup, TableH5CardCash, agentId)
	o := NewOrm(multiOrm, DBChessCenter)
	var user []orm.Params
	_, err := o.Raw(sql).Values(&user)
	if CheckError(err) {
		return user, err
	}
	return user, nil
}

//代理登录详细情况
func AgentLoginLog(p ListParams, t ListDayParams, uid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	condition := fmt.Sprintf("uid = %v", uid)
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		condition = fmt.Sprintf("uid = %v AND login_time >= %v AND login_time <= %v ", uid, t.StartTime, t.EndTime)
	}
	sql := fmt.Sprintf(`
		SELECT
			login_time,ip
		FROM
			%v
		WHERE
			%v
		ORDER BY
			login_time DESC
		LIMIT ?,?`,
		TableAgentLoginLog, condition)
	o := NewOrm(multiOrm, DBChessLog)
	var log []orm.Params
	n, err := o.Raw(sql, limit, p.PageSize).Values(&log)
	if err != nil || n == 0 { //没有数据可查
		return log, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			%v`,
		TableAgentLoginLog, condition)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return log, 0, err
	}
	return log, count, nil
}

//只要正式代理(一级及二级)
func ListChildAgent(p ListParams, uid, isFormal int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" u.pid = %v", uid)
	if isFormal == 1 {
		where = fmt.Sprintf(" u.pid = %v AND u.status = %v", uid, FirstTopUpSuccess)
	}
	sql := fmt.Sprintf(`
		SELECT
			g.name AS group_name,g.id AS group_id,
			u.*,
			c.card_num,c.amount,c.total_card_num,c.open_fee
		FROM
			%v AS u
		LEFT JOIN
			%v AS g
		ON u.group_id = g.id
		LEFT JOIN
			%v AS c
		ON u.uid = c.uid
		WHERE
			%v
		ORDER BY
			u.create_time DESC
		LIMIT ?,?
		`, TableH5User, TablePcGroup, TableH5CardCash, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if CheckError(err) {
		return user, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS u WHERE %v`, TableH5User, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return user, count, err
	}
	return user, count, nil
}
